// stores/currency.ts
import {defineStore} from 'pinia'
import {getRateList} from "../api";
// @ts-ignore - Ignoring type issues with cache module import
import { CurrencyAdapter } from "../utils/cache/currency-adapter";

interface Currency {
    id: string | number
    name: string
    unit: string
    cn_name: string
    currency_code: string,
    exchange_rate: number,
}

export const useCurrencyStore = defineStore('currency', {
    state: () => ({
        currentCurrency: CurrencyAdapter.getCurrentCurrency() || {} as Currency,
        currencies: CurrencyAdapter.getAllCurrencies() || [] as Currency[],
    }),
    actions: {
        async fetchCurrencies() {
            await getRateList().then((res) => {
                if (res.code === 200) {
                    if(res.data?.length > 0){
                        this.setCurrencies(res.data)
                        this.setCurrency(res.data[0])
                    }
                }
            })
        },
        setCurrency(currency: Currency) {
            this.currentCurrency = currency
            CurrencyAdapter.setCurrentCurrency(currency);
        },
        setCurrencies(currencies: Array<Currency>) {
            this.currencies = currencies
            CurrencyAdapter.setAllCurrencies(currencies);
        },
    },
    persist: {
        key: 'currency-store',
        storage: localStorage,
    }
})
